package com.lct.simpleforecast.mvp.model

import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.lct.simpleforecast.MyApplication
import com.lct.simpleforecast.bean.ForecastBean
import com.lct.simpleforecast.extensions.logE
import com.lct.simpleforecast.mvp.model.network.IRequest
import com.lct.simpleforecast.mvp.model.network.OkHttp
import com.lct.simpleforecast.mvp.model.network.Url
import okhttp3.Call

/**
 * Author：SkySmile
 * Date：2018/7/5
 * Description：MainActivity对应的model
 */
class MainModel {
    private val tag = "MainModel"

    /**
     * 通过高德地图获取位置信息（城市信息 + 城区信息）
     *
     * @param request 执行请求的IRequest接口
     */
    fun getLocationInfoByAMap(request: IRequest<String>) {
        if (MyApplication.instance.isNetworkAvailable()) {
            //初始化定位
            val aMapLocationClient = AMapLocationClient(MyApplication.instance)
            //设置定位回调监听
            aMapLocationClient.setLocationListener {
                if (it.errorCode == 0) {
                    //定位成功  城市信息 + 城区信息
                    //request.onSuccess("${it.city}-${it.district}")
                    //城区信息
                    request.onSuccess(it.district)
                    //销毁定位客户端，同时销毁本地定位服务
                    aMapLocationClient.onDestroy()
                } else {
                    val aMapErrorMsg = "AMap location error，errorCode：${it.errorCode}，" +
                            "errorInfo：${it.errorInfo}"
                    aMapErrorMsg.logE(tag)
                    request.onFailure(aMapErrorMsg)
                    //销毁定位客户端，同时销毁本地定位服务
                    aMapLocationClient.onDestroy()
                }
            }
            //初始化AMapLocationClientOption对象
            val option = AMapLocationClientOption()
            //获取最近3s内精度最高的一次定位结果
            option.isOnceLocationLatest = true
            //给定位客户端对象设置定位参数
            aMapLocationClient.setLocationOption(option)
            //启动定位
            aMapLocationClient.startLocation()
        } else {
            request.onNetworkError()
        }
    }

    /**
     * 获取天气数据
     *
     * @param location 城市名称 | 城区名称 （上海 | 浦东新区）
     * @param request 请求回调接口
     */
    fun getForecastData(location: String, request: IRequest<ForecastBean>): Call? {
        val url = "${Url.forecastUrl}?key=${Url.heWeatherKey}&location=$location"
        return OkHttp.doGet(url, request)
    }

}